/** 
 ** Copyright (c) 2010 Ushahidi Inc
 ** All rights reserved
 ** Contact: team@ushahidi.com
 ** Website: http://www.ushahidi.com
 ** 
 ** GNU Lesser General Public License Usage
 ** This file may be used under the terms of the GNU Lesser
 ** General Public License version 3 as published by the Free Software
 ** Foundation and appearing in the file LICENSE.LGPL included in the
 ** packaging of this file. Please review the following information to
 ** ensure the GNU Lesser General Public License version 3 requirements
 ** will be met: http://www.gnu.org/licenses/lgpl.html.	
 **	
 **
 ** If you have questions regarding the use of this file, please contact
 ** Ushahidi developers at team@ushahidi.com.
 ** 
 **/

package com.ushahidi.android.app;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.location.Address;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.MapView;
import com.google.android.maps.OverlayItem;
import com.ushahidi.android.app.AroundMeMap.MapMarker;
import com.ushahidi.android.app.AroundMeMap.HighSensitiveMultiTimeDeviceLocationListener;
import com.ushahidi.android.app.AroundMeMap.LowSensitiveOneTimeDeviceLocationListener;
import com.ushahidi.android.app.data.IncidentsData;
import com.ushahidi.android.app.data.ResourceData;
import com.ushahidi.android.app.data.UshahidiDatabase;
import com.ushahidi.android.app.net.AroundMeNetRequest;
import com.ushahidi.android.app.net.LinkedResourceNetRequest;
import com.ushahidi.android.app.ui.PullToRefreshListView;
import com.ushahidi.android.app.ui.PullToRefreshListView.OnRefreshListener;
import com.ushahidi.android.app.util.Util;

public class ListLinkedResources extends Activity {

    /** Called when the activity is first created. */
    private PullToRefreshListView listResource = null;

    private ListIncidentAdapter ila;

    private static final int HOME = Menu.FIRST + 1;

    private static final int ADD_INCIDENT = Menu.FIRST + 2;

    private static final int INCIDENT_MAP = Menu.FIRST + 3;

    private static final int INCIDENT_REFRESH = Menu.FIRST + 4;

    private static final int SETTINGS = Menu.FIRST + 5;

    private static final int ABOUT = Menu.FIRST + 6;

    private static final int GOTOHOME = 0;

    private static final int POST_INCIDENT = 1;

    private static final int INCIDENTS_MAP = 2;

    private static final int VIEW_INCIDENT = 3;

    private static final int REQUEST_CODE_SETTINGS = 1;

    private static final int REQUEST_CODE_ABOUT = 2;
    
    // Oceanmaster
    private static  double   holder_latitude;

    private static  double   holder_longitude;
    
    private static  double   MAP_SEARCH_RANGE= 0.05;          
    // end

    private static List<IncidentsData> NearbyResources;
    
    private Bundle                     extras;

    private String                     reportLatitude;

    private String                     reportLongitude;

    private String                     reportTitle;

    private String                     reportDescription;

    private static double              latitude;

    private static double              longitude;
    
    public List<Drawable>              markers;

    private boolean                    GPSUpdated            = false;

    // OceanMaster, used to mark if GPS is updated
    private Spinner spinner = null;

    private ArrayAdapter<String> spinnerArrayAdapter;

    private Bundle resourcesBundle = new Bundle();

    private final Handler mHandler = new Handler();

    public static UshahidiDatabase mDb;

    private List<IncidentsData> mOldResources;

    private Vector<String> vectorCategories = new Vector<String>();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.list_incidents);
        spinner = (Spinner)findViewById(R.id.incident_cat);
        spinner.setVisibility(View.INVISIBLE);
        UshahidiPref.IncidentID2Link=getIntent().getExtras().getInt("InID")+"";
        
        listResource = (PullToRefreshListView)findViewById(R.id.view_incidents);
        listResource.setOnRefreshListener(new OnRefreshListener() {
            public void onRefresh() {
                refreshForReports();
            }
        });
        mOldResources = new ArrayList<IncidentsData>();
        ila = new ListIncidentAdapter(this);
        listResource.setOnItemClickListener(new OnItemClickListener() {

            public void onItemClick(AdapterView<?> arg0, View view, int positions, long id) {
                
                //It seems pull to refresh list is buggy; The list item position item is by 1 higher
                //TODO Look into fixing this.
                int position = positions - 1;
                
                resourcesBundle.putInt("id", mOldResources.get(position).getIncidentId());
                resourcesBundle.putString("title", mOldResources.get(position).getIncidentTitle());
                resourcesBundle.putString("desc", mOldResources.get(position).getIncidentDesc());
                resourcesBundle.putString("longitude", mOldResources.get(position)
                        .getIncidentLocLongitude());
                resourcesBundle.putString("latitude", mOldResources.get(position)
                        .getIncidentLocLatitude());
                resourcesBundle.putString("category", mOldResources.get(position)
                        .getIncidentCategories());
                resourcesBundle.putString("location", mOldResources.get(position)
                        .getIncidentLocation());
                resourcesBundle.putString("date", mOldResources.get(position).getIncidentDate());
                resourcesBundle.putString("media", mOldResources.get(position)
                        .getIncidentThumbnail());
                resourcesBundle.putString("image", mOldResources.get(position).getIncidentImage());
                resourcesBundle.putString("status", ""
                        + mOldResources.get(position).getIncidentVerified());

                Intent intent = new Intent(ListLinkedResources.this, ViewResource.class);
                intent.putExtra("resources", resourcesBundle);
                startActivityForResult(intent, VIEW_INCIDENT);
                setResult(RESULT_OK, intent);

            }

        });

        spinner = (Spinner)findViewById(R.id.incident_cat);

        mHandler.post(mDisplayResources);
        mHandler.post(mDisplayCategories);
        // mark all incidents as read
        UshahidiApplication.mDb.markAllIncidentssRead();
        UshahidiApplication.mDb.markAllCategoriesRead();

    }
    final Runnable mDisplayResources = new Runnable() {
        public void run() {
            setProgressBarIndeterminateVisibility(true);
            showResources(UshahidiPref.IncidentID2Link);
            //showCategories();
            try {
                setProgressBarIndeterminateVisibility(false);
            } catch (Exception e) {
                return; // means that the dialog is not showing, ignore please!
            }
        }
    };

    final Runnable mDisplayCategories = new Runnable() {
        public void run() {
            //showCategories();
        }
    };
    
    public void refreshForReports() {
        ReportsTask reportsTask = new ReportsTask();
        reportsTask.appContext = this;
        reportsTask.execute();
    }

    // menu stuff
    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        populateMenu(menu);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        populateMenu(menu);

        return (super.onCreateOptionsMenu(menu));
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // applyMenuChoice(item);

        return (applyMenuChoice(item) || super.onOptionsItemSelected(item));
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {

        return (applyMenuChoice(item) || super.onContextItemSelected(item));
    }

    private void populateMenu(Menu menu) {
        MenuItem i;
        i = menu.add(Menu.NONE, HOME, Menu.NONE, R.string.menu_home);
        i.setIcon(R.drawable.ushahidi_home);

        i = menu.add(Menu.NONE, ADD_INCIDENT, Menu.NONE, R.string.incident_menu_add);
        i.setIcon(R.drawable.ushahidi_add);

        i = menu.add(Menu.NONE, INCIDENT_MAP, Menu.NONE, R.string.incident_menu_map);
        i.setIcon(R.drawable.ushahidi_map);

        i = menu.add(Menu.NONE, INCIDENT_REFRESH, Menu.NONE, R.string.menu_sync);
        i.setIcon(R.drawable.ushahidi_refresh);

        i = menu.add(Menu.NONE, SETTINGS, Menu.NONE, R.string.menu_settings);
        i.setIcon(R.drawable.ushahidi_settings);

        i = menu.add(Menu.NONE, ABOUT, Menu.NONE, R.string.menu_about);
        i.setIcon(R.drawable.ushahidi_about);

    }

    private boolean applyMenuChoice(MenuItem item) {
        Intent intent;
        switch (item.getItemId()) {
            case HOME:
                intent = new Intent(ListLinkedResources.this, Ushahidi.class);
                startActivityForResult(intent, GOTOHOME);
                return true;
            case INCIDENT_REFRESH:
                refreshForReports();
                return (true);

            case INCIDENT_MAP:
                resourcesBundle.putInt("tab_index", 1);
                intent = new Intent(ListLinkedResources.this, IncidentsTab.class);
                intent.putExtra("tab", resourcesBundle);
                startActivityForResult(intent, INCIDENTS_MAP);
                return (true);

            case ADD_INCIDENT:
                intent = new Intent(ListLinkedResources.this, AddIncident.class);
                startActivityForResult(intent, POST_INCIDENT);
                return (true);

            case ABOUT:
                intent = new Intent(ListLinkedResources.this, About.class);
                startActivityForResult(intent, REQUEST_CODE_ABOUT);
                setResult(RESULT_OK);
                return true;

            case SETTINGS:
                intent = new Intent(ListLinkedResources.this, Settings.class);

                // Make it a subactivity so we know when it returns
                startActivityForResult(intent, REQUEST_CODE_SETTINGS);
                return (true);

        }
        return (false);
    }

    // thread class
    private class ReportsTask extends AsyncTask<Void, Void, Integer> {

        protected Integer status;

        protected Context appContext;

        @Override
        protected void onPreExecute() {
            setProgressBarIndeterminateVisibility(true);

        }

        @Override
        protected Integer doInBackground(Void... params) {
            status = Util.processReports(appContext);
            return status;
        }

        @Override
        protected void onPostExecute(Integer result) {
            if (result == 4) {
                Util.showToast(appContext, R.string.internet_connection);
            } else if (result == 3) {
                Util.showToast(appContext, R.string.invalid_ushahidi_instance);
            } else if (result == 2) {
                Util.showToast(appContext, R.string.could_not_fetch_reports);
            } else if (result == 1) {
                Util.showToast(appContext, R.string.could_not_fetch_reports);
            } else if (result == 0) {
            	showResources(UshahidiPref.IncidentID2Link);
 //               showCategories();
                Util.showToast(appContext, R.string.reports_successfully_fetched);
            }
            listResource.onRefreshComplete();
        }

    }
    // Query according to incident id for its linked resources
    // Directly use online api
    // Modified by yujie

    public  List<IncidentsData> QueryByInID(String by)
    {
	// TODO: change to web based data

    mOldResources.clear();// by OceanMaster

	JSONArray results;
	results = LinkedResourceNetRequest.getAllLinkedResourceFromWebByID(by);
//	results = AroundMeNetRequest.getNearByResourceFromWeb(UshahidiPref.NearByRadius, true,
//	        holder_latitude, holder_longitude,by);

	if (results == null)// 没有结果
	    return mOldResources;

	String title;
	String description;
	String location;
	String categories;
	String thumbnail;
	String image;

	try
	{

	    for (int i = 0; i < results.length(); i++)
	    {
		JSONObject cursor = results.optJSONObject(i);

		JSONObject resource_cate = cursor.getJSONObject("resource_category");
		String resource_id = resource_cate.getString("resource_id");
		ResourceData  resourceData = new ResourceData();
		resourceData.setDataFromCursor(UshahidiApplication.mDb.fetchResourceById(resource_id));
		mOldResources.add(resourceData);
	    }
	    return mOldResources;
	}
	catch (JSONException e)
	{
		mOldResources.clear();
	}

	return mOldResources;
    }

    // get resource from the db
    public void showResources(String by) {

    	//Modified by yujie chen
    	mOldResources.clear();
        String title;
        String status;
        String date;
        String description;
        String location;
        String categories;
        String media;
        String image;
        String thumbnails[];
        Drawable d = null;
    	mOldResources=this.QueryByInID(by);
    	if(!mOldResources.isEmpty())
    	{
            ila.removeItems();
            ila.notifyDataSetChanged();
    		Iterator<IncidentsData> it= mOldResources.iterator();
    		while(it.hasNext())
    		{
    			ListIncidentText listText = new ListIncidentText();
    			IncidentsData resourceData= (IncidentsData)it.next();     
                listText.setTitle(resourceData.getIncidentTitle());
                listText.setDesc(resourceData.getIncidentDesc());
                listText.setCategories(resourceData.getIncidentCategories());
                listText.setLocation(resourceData.getIncidentLocation());
                listText.setDate(resourceData.getIncidentDate());
                media = resourceData.getIncidentThumbnail();
                listText.setMedia(media);
                thumbnails = media.split(",");
                // TODO do a proper check for thumbnails
                if (!TextUtils.isEmpty(thumbnails[0])) {
                    d = ImageManager.getImages(thumbnails[0]);
                } else {
                    d = null;
                }
                listText.setThumbnail(d == null ? getResources().getDrawable(
                        R.drawable.ushahidi_report_icon) : d);

                //image = resourceData.getIncidentImage();
                //resourceData.setResourceImage(image);

                status = resourceData.getIncidentVerified() == 0 ? getString(R.string.report_unverified)
                        : getString(R.string.report_verified);
                listText.setStatus(status);

                listText.setId(resourceData.getIncidentId());
                listText.setArrow(getResources().getDrawable(R.drawable.ushahidi_arrow));
                ila.addItem(listText);
    		}
    	}
    	else{
    		
    		
	    	Cursor cursor;
	        if ( by.length()==0 ||by.equals(UshahidiPref.all))
	            cursor = UshahidiApplication.mDb.fetchAllResources();
	        else
	            cursor = UshahidiApplication.mDb.fetchNearByResourceByCatId(holder_latitude,holder_longitude,MAP_SEARCH_RANGE,by);
	        if (cursor.moveToFirst()) {
	            int idIndex = cursor.getColumnIndexOrThrow(UshahidiDatabase.RESOURCE_ID);
	            int titleIndex = cursor.getColumnIndexOrThrow(UshahidiDatabase.RESOURCE_TITLE);
	            int dateIndex = cursor.getColumnIndexOrThrow(UshahidiDatabase.RESOURCE_DATE);
	            int verifiedIndex = cursor.getColumnIndexOrThrow(UshahidiDatabase.RESOURCE_VERIFIED);
	            int locationIndex = cursor.getColumnIndexOrThrow(UshahidiDatabase.RESOURCE_LOC_NAME);
	
	            int descIndex = cursor.getColumnIndexOrThrow(UshahidiDatabase.RESOURCE_DESC);
	
	            int categoryIndex = cursor.getColumnIndexOrThrow(UshahidiDatabase.RESOURCE_CATEGORIES);
	
	            int mediaIndex = cursor.getColumnIndexOrThrow(UshahidiDatabase.RESOURCE_MEDIA);
	
	            int imageIndex = cursor.getColumnIndexOrThrow(UshahidiDatabase.RESOURCE_IMAGE);
	
	            int latitudeIndex = cursor
	                    .getColumnIndexOrThrow(UshahidiDatabase.RESOURCE_LOC_LATITUDE);
	
	            int longitudeIndex = cursor
	                    .getColumnIndexOrThrow(UshahidiDatabase.RESOURCE_LOC_LONGITUDE);
	
	            ila.removeItems();
	            ila.notifyDataSetChanged();
	            mOldResources.clear();
	
	            do {
	            	ListIncidentText listText = new ListIncidentText();
	                ResourceData resourceData = new ResourceData();
	                mOldResources.add(resourceData);
	
	                int id = Util.toInt(cursor.getString(idIndex));
	                resourceData.setResourceId(id);
	                resourceData.setResourceLocLatitude(cursor.getString(latitudeIndex));
	                resourceData.setResourceLocLongitude(cursor.getString(longitudeIndex));
	
	                title = cursor.getString(titleIndex);
	                resourceData.setResourceTitle(title);
	                listText.setTitle(Util.capitalize(title));
	
	                description = cursor.getString(descIndex);
	                resourceData.setResourceDesc(description);
	                listText.setDesc(description);
	
	                categories = cursor.getString(categoryIndex);
	                resourceData.setResourceCategories(categories);
	                listText.setCategories(Util.capitalize(categories));
	
	                location = cursor.getString(locationIndex);
	                resourceData.setResourceLocation(location);
	                listText.setLocation(Util.capitalize(location));
	
	                date = Util.formatDate("yyyy-MM-dd HH:mm:ss", cursor.getString(dateIndex),
	                        "MMMM dd, yyyy 'at' hh:mm:ss aaa");
	
	                resourceData.setResourceDate(date);
	                listText.setDate(date);
	
	                media = cursor.getString(mediaIndex);
	                resourceData.setResourceThumbnail(media);
	                listText.setMedia(media);
	
	                
	                thumbnails = media.split(",");
	                // TODO do a proper check for thumbnails
	                if (!TextUtils.isEmpty(thumbnails[0])) {
	                    d = ImageManager.getImages(thumbnails[0]);
	                } else {
	                    d = null;
	                }
	
	                listText.setThumbnail(d == null ? getResources().getDrawable(
	                        R.drawable.ushahidi_report_icon) : d);
	
	                image = cursor.getString(imageIndex);
	                resourceData.setResourceImage(image);
	
	                status = Util.toInt(cursor.getString(verifiedIndex)) == 0 ? getString(R.string.report_unverified)
	                        : getString(R.string.report_verified);
	                resourceData.setResourceVerified(Util.toInt(cursor.getString(verifiedIndex)));
	                listText.setStatus(status);
	
	                listText.setId(id);
	                listText.setArrow(getResources().getDrawable(R.drawable.ushahidi_arrow));
	                ila.addItem(listText);
	            } while (cursor.moveToNext());
                cursor.close();
	        }
	    }
        ila.notifyDataSetChanged();
        listResource.setAdapter(ila);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
    }
    
    /********************
     * Main Life Cycle OceanMaster
     ********************/

    @Override
    public void onResume()
    {
	Log.v("Oceanmaster", "Around Me Resumed");
	super.onResume();
    }

    @Override
    protected void onDestroy()
    {
	
	super.onDestroy();
    }

    @Override
    protected void onPause()
    {

    	//GPSUpdated = false;
	// SharedPreferences.Editor editor = getPreferences(0).edit();
	// editor.putString("title", mIncidentTitle.getText().toString());
	// editor.putString("desc", mIncidentDesc.getText().toString());
	// editor.putString("location", mIncidentLocation.getText().toString());
	// editor.commit();
	super.onPause();
    }

    @Override
    protected void onStop()
    {
	super.onStop();
    }

 
}
